<template>
  <div class="components-score-prod-sku-table mod-prod-sku-table">
    <el-form-item
      :label="$t('prodSku.priceAndInventory')"
      :label-width="$t('language') === 'English' ? '150px' : '130px'"
    >
      <div class="sku-table-con">
        <!--批量设置-->
        <div
          v-if="lists.length > 1"
          class="batch-settings-box"
        >
          <div class="set-txt">
            <span>{{
              $t("groups.batchSettings")
            }}</span>
            <span class="weak-txt">{{ $t("prodSku.postProductTips14") }}</span>
          </div>
          <div
            class="batch-settings-tb"
          >
            <el-form
              :inline="true"
              class="demo-form-inline"
              @submit.prevent
            >
              <div class="batch-settings-con">
                <div
                  v-for="(item, i) in batchList"
                  :key="i"
                  class="item"
                >
                  <el-select
                    v-model="item.value"

                    class="bat-set-item"
                    :placeholder="$t('tip.select')"
                    @change="onChangeValue"
                  >
                    <el-option
                      :key="-1"
                      :label="$t('date.a')"
                      :value="-1"
                    />
                    <el-option
                      v-for="(el,index) in item.tagItems"
                      :key="index"
                      :label="el.propValue"
                      :value="el.propValue"
                    />
                  </el-select>
                </div>

                <div class="item">
                  <input
                    v-model.number="dataFrom.oriPrice"
                    :placeholder="$t('prodList.marketValue')"
                    type="number"
                    :precision="2"
                    :max="100000000"
                    :min="0"
                    :step="0.01"
                    class="tag-input-width"
                    @blur="
                      onHandleInputValue(
                        dataFrom.oriPrice,
                        null,
                        'oriPrice',
                        0,
                        100000000
                      )
                    "
                  >
                </div>
                <div class="item">
                  <input
                    v-model.number="dataFrom.price"
                    :placeholder="$t('prodList.salesPrice')"
                    type="number"
                    :precision="2"
                    :max="100000000"
                    :min="0"
                    :step="0.01"
                    class="tag-input-width"
                    @blur="
                      onHandleInputValue(
                        dataFrom.price,
                        null,
                        'price',
                        0,
                        100000000
                      )
                    "
                  >
                </div>
                <div class="item">
                  <input
                    v-model.number="dataFrom.skuScore"
                    :placeholder="$t('product.scorePrice')"
                    type="number"
                    :max="100000000"
                    :min="1"
                    :step="1"
                    class="tag-input-width"
                    @keyup="
                      dataFrom.skuScore = String(dataFrom.skuScore).match(/[^0-9]/)
                        ? ''
                        : dataFrom.skuScore
                    "
                    @blur="
                      onHandleInputValue(
                        dataFrom.skuScore,
                        null,
                        'skuScore',
                        1,
                        100000000
                      )
                    "
                  >
                </div>
                <div class="item">
                  <input
                    v-model.number="dataFrom.stocks"
                    :placeholder="$t('product.stocks')"
                    type="number"
                    :max="9999999"
                    :min="0"
                    :step="1"
                    class="tag-input-width"
                    @keyup="
                      dataFrom.stocks = String(dataFrom.stocks).match(/[^0-9]/)
                        ? ''
                        : dataFrom.stocks
                    "
                    @blur="
                      onHandleInputValue(
                        dataFrom.stocks,
                        null,
                        'stocks',
                        0,
                        9999999
                      )
                    "
                  >
                </div>
                <div class="item">
                  <input
                    v-model.number="dataFrom.weight"
                    :placeholder="$t('prodList.prodWeight')"
                    type="number"
                    :max="100000000"
                    :min="0"
                    :step="0.01"
                    class="tag-input-width"
                    @blur="
                      onHandleInputValue(
                        dataFrom.weight,
                        null,
                        'weight',
                        0,
                        100000000
                      )
                    "
                  >
                </div>
                <div class="item">
                  <input
                    v-model.number="dataFrom.volume"
                    :placeholder="$t('prodList.prodVolume')"
                    type="number"
                    :max="100000000"
                    :min="0"
                    :step="0.01"
                    class="tag-input-width"
                    @blur="
                      onHandleInputValue(
                        dataFrom.volume,
                        null,
                        'volume',
                        0,
                        100000000
                      )
                    "
                  >
                </div>
                <div class="item" />
                <div class="btn-row">
                  <div
                    class="default-btn primary-btn"
                    @click="onBatchSet"
                  >
                    {{ $t("crud.saveBtn") + $t("groups.batchSettings") }}
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </div>
        <!--sku列表-->
        <div class="table-con">
          <el-table
            :key="tableKey"
            :data="lists"
            header-cell-class-name="table-header"
            :span-method="tableSpanMethod"
            row-class-name="table-row"
            border
          >
            <el-table-column
              v-for="(leftTitle, index) in tableLeftTitles"
              :key="index"
              :label="
                $t('language') === 'English'
                  ? leftTitle.tagNameEn
                  : leftTitle.tagName
              "
            >
              <!-- scope.row.propertiesEn &&  -->
              <template #default="scope">
                <div v-if="scope.row.properties">
                  {{
                    scope.row.properties.split(";")[index].substring(scope.row.properties.split(";")[index].indexOf(':') + 1)
                  }}
                </div>
              </template>
            </el-table-column>
            <!-- 市场价 -->
            <el-table-column
              prop="oriPrice"
              :label="$t('prodList.marketValue')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.oriPrice"
                  type="number"
                  :precision="2"
                  :max="100000000"
                  :min="0"
                  :step="0.01"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @blur="
                    onHandleInputValue(
                      scope.row.oriPrice,
                      scope.$index,
                      'oriPrice',
                      0,
                      100000000
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 售价 -->
            <el-table-column
              prop="price"
              :label="$t('prodList.salesPrice')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.price"
                  type="number"
                  :precision="2"
                  :max="100000000"
                  :min="0"
                  :step="0.01"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @blur="
                    onHandleInputValue(
                      scope.row.price,
                      scope.$index,
                      'price',
                      0,
                      100000000
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 积分价 -->
            <el-table-column
              prop="skuScore"
              :label="$t('product.scorePrice')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.skuScore"
                  type="number"
                  :max="100000000"
                  :min="1"
                  :step="1"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @keyup="
                    scope.row.skuScore = String(scope.row.skuScore).match(/[^0-9]/)
                      ? ''
                      : scope.row.skuScore
                  "
                  @blur="
                    onHandleInputValue(
                      scope.row.skuScore,
                      scope.$index,
                      'skuScore',
                      1,
                      100000000
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 库存 -->
            <el-table-column
              prop="stocks"
              :label="$t('product.stocks')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.stocks"
                  type="number"
                  :max="9999999"
                  :min="0"
                  :step="1"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @keyup="
                    scope.row.stocks = String(scope.row.stocks).match(/[^0-9]/)
                      ? ''
                      : scope.row.stocks
                  "
                  @blur="
                    onHandleInputValue(
                      scope.row.stocks,
                      scope.$index,
                      'stocks',
                      0,
                      9999999
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 重量 -->
            <el-table-column
              prop="weight"
              :label="$t('prodList.prodWeight')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.weight"
                  type="number"
                  :max="100000000"
                  :min="0"
                  :step="0.01"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @blur="
                    onHandleInputValue(
                      scope.row.weight,
                      scope.$index,
                      'weight',
                      0,
                      100000000
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 体积 -->
            <el-table-column
              prop="volume"
              :label="$t('prodList.prodVolume')"
            >
              <template #default="scope">
                <input
                  v-model.number="scope.row.volume"
                  type="number"
                  :max="100000000"
                  :min="0"
                  :step="0.01"
                  :disabled="!scope.row.status"
                  class="tag-input-width"
                  @blur="
                    onHandleInputValue(
                      scope.row.volume,
                      scope.$index,
                      'volume',
                      0,
                      100000000
                    )
                  "
                >
              </template>
            </el-table-column>
            <!-- 编码 -->
            <el-table-column
              prop="partyCode"
              :label="$t('product.prodCode')"
              width="220px"
            >
              <template #default="scope">
                <input
                  ref="partyCodeIntRef"
                  v-model="scope.row.partyCode"
                  type="text"
                  maxlength="36"
                  :disabled="!scope.row.status"
                  class="tag-input-width text-input party-code"
                  @blur="onValidatePartyCode(scope)"
                >
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('text.menu')"
              align="center"
            >
              <!-- :width="$t('language') === 'English' ? '210' : '120'" -->
              <template #default="scope">
                <div
                  v-if="scope.row.status"
                  class="default-btn text-btn"
                  @click="onChangeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("publics.disable") }}
                </div>
                <div
                  v-else
                  class="default-btn text-btn"
                  @click="onChangeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("shop.ena") }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form-item>
  </div>
</template>

<script setup>

import { validNoEmptySpace } from '@/utils/validate'
import { flatten as genFlatten } from '@/utils'
// import PicUpload from '@/components/pic-upload'
import { ElMessage } from 'element-plus'

const emit = defineEmits([
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  // eslint-disable-next-line vue/require-prop-types
  prodNameCn: {
    default: ''
  },
  // eslint-disable-next-line vue/require-prop-types
  prodNameEn: {
    default: ''
  }
})

const batchList = ref([])
// 表格数据
const lists = ref([])
const rowspan = ref([])
// 根据选定的规格所查询出来的规格值
// initing: false
const isEdit = ref(false)
const dataFrom = reactive({
  oriPrice: null,
  price: null,
  skuScore: null,
  stocks: null,
  weight: null,
  volume: null
})
const prodStore = useProdStore()
const skuTags = computed(() => {
  return prodStore.skuTags.filter((item) => {
    return !!(
      item.tagItems &&
            item.tagItems.length &&
            !item.tagItems[0].creating
    )
  })
})
const tableLeftTitles = computed(() => {
  const arr = []
  skuTags.value?.forEach((el, i) => {
    arr[i] = { ...(batchList.value[i] || {}), ...el }
  })
  batchList.value = arr
  batchList.value.forEach(el => {
    if (!el.value) {
      el.value = -1
    }
  })
  return skuTags.value
})

const tableKey = ref(Symbol(tableLeftTitles.value))
watch(() => tableLeftTitles.value, () => {
  tableKey.value = Symbol(tableLeftTitles.value)
}, {
  deep: true
})

const defalutSku = computed(() => {
  return prodStore.defalutSku
})
watch(() => lists.value, () => {}, {
  deep: true,
  immediate: true
})

watch(() => props.prodNameCn, () => {
  skuAddProdName()
})
watch(() => props.prodNameEn, () => {
  skuAddProdName()
})
watch(() => rowspan.value, () => {})

onMounted(function () {
  isEdit.value = false
  if (!lists.value.length) {
    lists.value.push({
      oriPrice: 0.01,
      partyCode: '',
      price: 0.01,
      prodName: '',
      status: 1,
      stocks: 0,
      volume: 0,
      weight: 0,
      skuScore: 0
    })
  }
})

const init = (skuList) => {
  // initing = true
  lists.value = genFlatten(skuTags.value, skuList, defalutSku.value)
  computeRowspan()
}
defineExpose({ init })
// eslint-disable-next-line no-unused-vars
const checkIsEqualByIndex = (str1, str2, index, splitStr = ':') => {
  const strArr1 = str1.split(';')
  const strArr2 = str2.split(';')
  const temp1 = [strArr1[index].slice(0, strArr1[index].indexOf(':')), strArr1[index].substring(strArr1[index].indexOf(':') + 1)]
  const temp2 = [strArr2[index].slice(0, strArr2[index].indexOf(':')), strArr2[index].substring(strArr2[index].indexOf(':') + 1)]
  return temp1[1] === temp2[1]
}
const computeRowspan = () => {
  rowspan.value = []
  const _rowspan = (index) => {
    const span = []
    let dot = 0
    lists.value.map((item, idx) => {
      if (idx === 0) {
        span.push(1)
      } else {
        if (
          checkIsEqualByIndex(
            item.properties,
            lists.value[idx - 1].properties,
            index
          )
        ) {
          span[dot] += 1
          span.push(0)
        } else {
          dot = idx
          span.push(1)
        }
      }
      return item
    })

    rowspan.value.push(span)
  }
  skuTags.value.map((item, index) => {
    _rowspan(index)
    return item
  })
}
watch(() => skuTags.value, () => {
  lists.value = genFlatten(skuTags.value, lists.value, defalutSku.value)
  computeRowspan()
  emit('update:modelValue', lists.value)
}, {
  deep: true,
  immediate: true
})

// eslint-disable-next-line no-unused-vars
const tableSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  for (let i = 0; i < skuTags.value.length; i++) {
    if (columnIndex === i) {
      if (rowspan.value[i] && rowspan.value[i][rowIndex]) {
        return {
          rowspan: rowspan.value[i][rowIndex],
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  }
}
const onChangeSkuStatus = (tagIndex) => {
  lists.value[tagIndex].status = lists.value[tagIndex].status ? 0 : 1
  emit('update:modelValue', lists.value)
}
const skuAddProdName = () => {
  // if (initing) {
  //   return
  // }
  const skuList = []
  emit('update:modelValue', lists.value)
  for (let i = 0; i < lists.value.length; i++) {
    const sku = Object.assign({}, lists.value[i])
    if (!sku.properties) {
      return
    }
    sku.skuName = ''
    sku.skuNameEn = ''
    const properties = sku.properties.split(';')
    for (const propertiesKey in properties) {
      sku.skuName += properties[propertiesKey].substring(properties[propertiesKey].indexOf(':') + 1) + ' '
    }
    sku.prodNameCn = props.prodNameCn + ' ' + sku.skuName
    sku.prodName = props.prodNameCn + ' ' + sku.skuName
    sku.prodNameEn = props.prodNameEn + ' ' + sku.skuNameEn
    skuList.push(sku)
  }
  emit('update:modelValue', skuList)
}

const onSwitchSet = () => {
  isEdit.value = !isEdit.value
  if (!isEdit.value) {
    dataFrom.oriPrice = null
    dataFrom.price = null
    dataFrom.stocks = null
    dataFrom.weight = null
    dataFrom.volume = null
    dataFrom.skuScore = null
    dataFrom.partyCode = ''
  }
}
const onChangeValue = () => {
  // $forceUpdate() // 刷新
}
const onBatchSet = () => {
  lists.value.forEach((sku) => {
    let isBatch = true
    sku.properties.split(';').forEach((el, index) => {
      // -1为全部
      if (batchList.value[index] && batchList.value[index].value !== -1 && el !== (batchList.value[index].tagName + ':' + batchList.value[index].value)) {
        isBatch = false
      }
    })
    if (isBatch) {
      if (dataFrom.oriPrice || dataFrom.oriPrice === 0) {
        sku.oriPrice = dataFrom.oriPrice
      }
      if (dataFrom.price || dataFrom.price === 0) {
        sku.price = dataFrom.price
      }
      if (dataFrom.stocks || dataFrom.stocks === 0) {
        sku.stocks = dataFrom.stocks
        // initing = false
      }
      if (dataFrom.weight || dataFrom.weight === 0) {
        sku.weight = dataFrom.weight
      }
      if (dataFrom.volume || dataFrom.volume === 0) {
        sku.volume = dataFrom.volume
      }
      if (dataFrom.skuScore || dataFrom.skuScore === 0) {
        sku.skuScore = dataFrom.skuScore
      }
    }
  })
  // onSwitchSet()
  // isEdit.value = false
  skuAddProdName()
}

/**
 * 处理输入框数据
 * @param data
 * @param index
 * @param dataFields
 * @param min 最小值
 * @param max 最大值
 */
const onHandleInputValue = (data, index, dataFields, min, max) => {
  if (index !== undefined && index !== null) {
    // 表格
    if (+data > max) {
      lists.value[index][dataFields] = max
      if (dataFields === 'stocks') {
        emit('update:modelValue', lists.value)
      }
    } else if (+data <= min || !data) {
      lists.value[index][dataFields] = min
      if (dataFields === 'stocks') {
        emit('update:modelValue', lists.value)
      }
    } else if (
      dataFields === 'price' ||
      dataFields === 'oriPrice' ||
      dataFields === 'volume' ||
      dataFields === 'weight' ||
      dataFields === 'skuScore'
    ) {
      lists.value[index][dataFields] = checkInput(data)
    }
  } else {
    // 批量
    if (data === null || data === '') {
      //
    } else if (+data > max) {
      dataFrom[dataFields] = max
    } else if (+data <= min) {
      dataFrom[dataFields] = min
      return
    } else if (
      dataFields === 'price' ||
      dataFields === 'oriPrice' ||
      dataFields === 'volume' ||
      dataFields === 'weight' ||
      dataFields === 'skuScore'
    ) {
      dataFrom[dataFields] = checkInput(data)
    }
  }
  // if (dataFields === 'stocks') {
  emit('update:modelValue', lists.value)
  // }
}

/**
 * 只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = String(num).replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = tmpVal.split('.').length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

/**
 * 编码输入框校验
 */
const onValidatePartyCode = (scope) => {
  const { row, $index } = scope
  // 纯空格校验
  if (validNoEmptySpace(row.partyCode)) {
    lists.value[$index].partyCode = ''
    return
  }
  // 商品编码重复校验
  check(row, $index)
}

const check = (row, $index) => {
  if (
    row.partyCode &&
    lists.value.find(
      (el, index) =>
        el.partyCode && index !== $index && el.partyCode === row.partyCode
    )
  ) {
    ElMessage({
      message: $t('product.postProductTips16'),
      type: 'error',
      duration: 1500
    })
  }
}

</script>

<style lang="scss" scoped>
.components-score-prod-sku-table.mod-prod-sku-table {
  // eslint-disable-next-line vue-scoped-css/no-unused-selector
  .pic-uploader-component .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  // eslint-disable-next-line vue-scoped-css/no-unused-selector
  .pic-uploader-component .el-upload:hover {
    border-color: #409eff;
  }

  // 表格输入框
  .tag-input-width {
    width: 100%;
    padding-left: 5px;
    padding-right: 0;
    border: 1px solid #dcdcdc;
    border-radius: 2px;
    height: 32px;
    line-height: 32px;
    box-sizing: border-box;
    &:focus {
      outline: 0;
    }
  }
  .tag-input-width.text-input {
    padding-right: 5px;
  }
  // 表格+批量设置
  .sku-table-con {
    display: block;
    padding: 10px;
    border: 1px solid #dcdcdc;
    width: 100%;
    box-sizing: border-box;
    // 批量设置
    .batch-settings-box {
      .set-txt {
        padding-top: 10px;
        .weak-txt {
          color: #999;
          font-size: 12px;
          margin-left: 5px;
        }
      }
      .batch-settings-tb {
        margin: 10px 0;
        // 头部
        ul,
        li {
          list-style: none;
          margin: 0;
          padding: 0;
          line-height: 1em;
        }
        .batch-settings-Head {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 15px 0;
          background: #f8f8f8;
          li.head-item {
            flex: 1;
            padding: 0 10px;
            font-weight: bold;
          }
          .coding {
            width: 220px;
          }
        }

        .batch-settings-con {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 15px 0;
          .item {
            flex: 1;
            padding: 0 10px;
            & :deep(.el-form-item),
            & :deep(.el-form-item__content) {
              width: 100%;
              margin-right: 0;
            }
          }
          .btn-row{
            width: 220px;
            text-align: right;
          }
        }
      }
    }
  }
}

.filter-submitBtn span {
  color: #fff !important;
}
div :deep(.el-table tbody tr:hover > td) {
  background-color: #ffffff;
}
</style>
